<template>
  <ex-dialog width="50%" class="ex-diolog" :title="title" :visible="visible" :close-on-click-modal="false"
    @closeDialog="handleClose">
    <div class="main" v-loading="loading">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" class="demo-ruleForm">
        <el-form-item label="专题分类名称：" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请填写专题分类名称" maxlength="10" show-word-limit style="width:280px">
          </el-input>
        </el-form-item>
        <el-form-item label="专题排序：" prop="sort">
          <el-input v-model="ruleForm.sort" placeholder="请输入" style="width:280px"></el-input>
        </el-form-item>
        <el-form-item label="是否显示：" prop="">
          <el-switch v-model="ruleForm.status" active-text="开" inactive-text="关" active-value="1" inactive-value="2">
          </el-switch>
        </el-form-item>
        <el-form-item label="分类标签：" prop="">
          <el-switch v-model="ruleForm.labelStatus" active-text="开" inactive-text="关" active-value="1"
            inactive-value="2">
          </el-switch>
        </el-form-item>
        <el-form-item label="" prop="label" v-if="ruleForm.labelStatus=='1'">
          <el-input v-model="ruleForm.label" placeholder="请填写标签" style="width:280px">
          </el-input>
        </el-form-item>
        <el-form-item label="商家店铺名称：" prop="merchantIdList">
          <el-select v-model="ruleForm.merchantIdList" placeholder="请选择商家店铺名称" multiple filterable style="width:280px"
            @change="shopChange">
            <el-option v-for="item in options" :key="item.id" :label="item.value" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="团购商品：" prop="goodsList">
          <el-select v-model="ruleForm.goodsList" placeholder="请选择团购商品" multiple filterable style="width:400px"
            value-key="id" @change="goodsChange">
            <el-option v-for="item in optionsTwo" :key="item.id" :label="item.value" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="" v-if="grouponIdList.length>0">
          <div class="list_box">
            <div class="list_box_s" v-for="(item,indexs) in grouponIdList" :key="indexs">
              <div class="list_box_s_l">{{item.value}}</div>
              <div class="list_box_s_r">
                <p class="el-icon-caret-top" v-if="indexs != 0" @click="leftMove(indexs)"></p>
                <p class="el-icon-caret-bottom" v-if="indexs + 1 != grouponIdList.length" @click="rigthtMove(indexs)">
                </p>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="button_box">
      <el-button type="primary" :loading="AgreeDisable" @click="submitForm('ruleForm')" v-if="id==null">立即创建</el-button>
      <el-button type="primary" :loading="AgreeDisable" @click="editForm('ruleForm')" v-if="id!=null">保存</el-button>
      <el-button @click="handleClose">取消</el-button>
    </div>
  </ex-dialog>
</template>
<script>
  // components
  import Loading from "@/components/Loading/index";
  // api
  import {
    merchantSelect,
    grouponSelect,
    configureAdd,
    configureGetInfo,
    configureEdit,
  } from "@/api/operateActive";

  export default {
    components: {
      Loading,
    },
    props: {
      visible: Boolean,
      id: String,
    },
    data() {
      return {
        title: '添加专题',
        loading: false,
        action: process.env.VUE_APP_BASE_API + "/common/v1/uploadFile",
        imgLoading: false,
        info: {},
        AgreeDisable: false,
        options: [],
        optionsTwo: [],
        grouponIdList: [
          // { name:'喜九重庆老火锅【超值双人套餐】',id:'1'},{ name:'【代金券】9.9抵50元代金券（全场通用可叠加2张）',id:'2'},{ name:'【新客专享】护肤三合一套餐*1次+单色美甲*1次',id:'3'},
        ],
        ruleForm: {
          name: '', //专题分类名称
          sort: '', //专题排序
          status: '1', //是否显示 1是 2 否
          labelStatus: '1', //分类标签状态;1是 2 否
          label: '', //分类标签
          merchantIdList: [], //商家店铺名称数组
          goodsList: [], //团购商品数组
          grouponIdList: [], //团购商品数组
        },
        rules: {
          name: [{
            required: true,
            message: "请输入专题分类名称",
            trigger: ["blur", "change"]
          }],
          sort: [{
            required: true,
            message: "请输入专题排序",
            trigger: ["blur", "change"]
          }],
          label: [{
            required: true,
            message: "请输入分类标签",
            trigger: ["blur", "change"]
          }],
          merchantIdList: [{
            required: true,
            message: "请选择店铺",
            trigger: ['blur', 'change'],
          }],
          goodsList: [{
            required: true,
            message: "请选择团购商品",
            trigger: ['blur', 'change'],
          }],
        },
      };
    },
    computed: {},
    created() {
      this.getMerchantSelect()
      console.log(this.id)
      if (this.id != null) {
        this.title = '编辑专题'
        this.getBannerInfo()
      }
    },
    methods: {
      //取消
      handleClose(formName) {
        this.$emit("update:visible", false);
      },
      shopChange(e) { //店铺名称选择
        console.log(e)
        this.getGrouponSelect(e)
      },
      goodsChange(e) { //商品选择
        console.log(e)
        this.grouponIdList = e
      },
      getMerchantSelect() { //获取商家列表
        const params = {
          query: '',
        };
        merchantSelect(params).then((res) => {
          this.options = res.result;
        });
      },
      getGrouponSelect(e) { //获取商品列表
        // console.log(this.grouponIdList)
        // this.ruleForm.goodsList = []
        // this.grouponIdList = []
        let list = e
        const data = {
          name: '',
          merchantIdList: list
        };
        // return
        grouponSelect(data).then((res) => {
          this.optionsTwo = res.result;
          console.log('this.optionsTwo', this.optionsTwo)
          console.log('this.grouponIdList', this.grouponIdList)

          let newarr = [] //筛选已选择店铺的商品
          this.optionsTwo.map(item => {
            this.grouponIdList.map(list => {
              if (item.id === list.id) {
                newarr.push({
                  id: list.id,
                  additionalValue: list.additionalValue,
                  value: list.value
                })
              }
            })
          })
          console.log('333', newarr);
          this.ruleForm.goodsList = newarr
          this.grouponIdList = newarr
        });
      },
      leftMove(index) {
        //上移
        if (index != 0) {
          this.grouponIdList[index] = this.grouponIdList.splice(
            index - 1,
            1,
            this.grouponIdList[index]
          )[0];
        } else {
          this.grouponIdList.push(this.grouponIdList.shift());
        }
      },
      rigthtMove(index) {
        //下移
        if (index != this.grouponIdList.length - 1) {
          this.grouponIdList[index] = this.grouponIdList.splice(
            index + 1,
            1,
            this.grouponIdList[index]
          )[0];
        } else {
          this.grouponIdList.unshift(this.grouponIdList.splice(index, 1)[0]);
        }
      },
      getBannerInfo() { //获取商家团购信息详情
        this.loading = true
        const params = {
          id: this.id
        };
        configureGetInfo(params).then((res) => {
          let info = res.result
          this.ruleForm.name = info.name
          this.ruleForm.sort = info.sort
          this.ruleForm.status = info.status
          this.ruleForm.labelStatus = info.labelStatus
          this.ruleForm.label = info.label
          this.ruleForm.merchantIdList = info.merchantIdList
          this.getGrouponSelect(info.merchantIdList)
          setTimeout(() => {
            this.grouponIdList = info.grouponList
            this.ruleForm.goodsList = info.grouponList
          }, 50)
          this.loading = false
        });
      },
      submitForm(formName) {
        //创建确定
        this.$refs[formName].validate((valid) => {
          if (valid) {
            //   alert("submit!");editGroupon
            // this.ruleForm.grouponIdList = this.grouponIdList
            let list = []
            this.grouponIdList.forEach((item) => {
              list.push(item.id)
            })
            this.ruleForm.grouponIdList = list
            console.log('成功', this.ruleForm)
            // return
            this.AgreeDisable = true
            var params = {
              ...this.ruleForm,
            };
            configureAdd(params).then((res) => {
                this.$message({
                  message: "保存成功",
                  type: "success",
                });
                setTimeout(() => {
                  this.$emit('success')
                  this.handleClose()
                  this.AgreeDisable = false
                }, 1000);
              })
              .finally(() => {
                this.AgreeDisable = false;
              });

          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
      editForm(formName) {
        //编辑确定
        this.$refs[formName].validate((valid) => {
          if (valid) {
            //   alert("submit!");editGroupon
            let list = []
            this.grouponIdList.forEach((item) => {
              list.push(item.id)
            })
            this.ruleForm.grouponIdList = list
            console.log('成功', this.ruleForm)
            // return
            this.AgreeDisable = true
            var params = {
              id: this.id,
              ...this.ruleForm,
            };
            configureEdit(params).then((res) => {
                this.$message({
                  message: "修改成功",
                  type: "success",
                });
                setTimeout(() => {
                  this.$emit('success')
                  this.handleClose()
                  this.AgreeDisable = false
                }, 1000);
              })
              .finally(() => {
                this.AgreeDisable = false;
              });

          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
    },
  };

</script>
<style lang="scss" scoped>
  .ex-diolog {
    ::v-deep .ex--dialog--footer {
      border: none !important;
      padding: 0 !important;
    }

    ::v-deep .ex--dialog--main {
      padding: 10px 20px !important;
    }
  }

  .main {
    padding: 20px 20px;
  }

  .list_box {
    width: 400px;
    border: 1px solid #dfe6ec;
    border-radius: 5px;
    padding: 5px 10px;
  }

  .list_box_s {
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #dfe6ec;
    padding: 5px 0;
  }

  .list_box_s:last-child {
    border-bottom: 0;
  }

  .list_box_s_l {
    font-size: 14px;
    color: #444;
    flex: 1;
    margin-right: 10px;
  }

  .list_box_s_r {
    width: 30px;
    display: flex;
    flex-direction: column;
    align-items: flex-end;
  }

  .list_box_s_r p {
    font-size: 20px;
    cursor: pointer;
  }

  .list_box_s_r p:hover {
    color: #1890ff;
  }

  .button_box {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px 0;
  }

</style>
